/* Copyright (C) 2008 Ryan Capote
 * This file is apart of Blue Engine
 * See Licesnse.txt
 */
#include "videoDriver.h"

namespace BlueEngine
{
    namespace Video
    {
	VideoDriver::VideoDriver()
	{
	    m_screen = NULL;         
	}

	VideoDriver::~VideoDriver()
	{
	    SDL_FreeSurface( m_screen );
	    SDL_Quit();
	}

	bool VideoDriver::setVideoMode(bool fullscreen, int width, int height,
				       int bits = 32)
	{
	    m_width = width;
	    m_height = height;

	    // Initialize SDL
	    if(SDL_Init(SDL_INIT_VIDEO) != 0)
	    {
		return false;
	    }

	    SDL_EnableUNICODE(1);

	    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, 
			        SDL_DEFAULT_REPEAT_INTERVAL); 
	
	    m_fullscreen = fullscreen;

	    int videoFlags = SDL_ANYFORMAT | SDL_OPENGL;

	    if( fullscreen )
		videoFlags |= SDL_FULLSCREEN;

	    // Enable double buffering
	    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	    m_screen = SDL_SetVideoMode( m_width, m_height, bits, videoFlags);

	    if(!m_screen)
		    return false;

	    // Setup OpenGL
	    glClearColor(0, 0, 0, 0);

	    glViewport(0, 0, m_width, m_height);
	   
	    // Default blend function
	    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

	    return true;

	}

	int VideoDriver::getWidth()
	{
	    return m_width;
	}

	int VideoDriver::getHeight()
	{
	    return m_height;
	}

	bool VideoDriver::isFullscreen()
	{
	    return m_fullscreen;
	}

	void VideoDriver::setCaption(std::string caption)
	{
	    SDL_WM_SetCaption(caption.c_str(), NULL); 
	}

	void VideoDriver::setBlend(bool blending)
	{
	    glEnable(GL_BLEND);
	}

	void VideoDriver::clip(int x, int y, int width, int height)
	{
	    glEnable(GL_SCISSOR_TEST);
	    glScissor(x, y, width, height);
	}

	void VideoDriver::clip(Utilities::Rect clipBox)
	{
	    clip(clipBox.x, clipBox.y, clipBox.width, clipBox.height);
	}

	void VideoDriver::resetClip()
	{
	    glScissor(0, 0, m_width, m_height);
	}

	void VideoDriver::beginScene()
	{
	    glClear(GL_COLOR_BUFFER_BIT);
	}

	void VideoDriver::endScene()
	{
	    if(glIsEnabled(GL_SCISSOR_TEST))
		glDisable(GL_SCISSOR_TEST);

	    SDL_GL_SwapBuffers();
	}

    }
}
